package com.scholarship.common.utils;

import com.upyun.RestManager;
import com.upyun.UpException;
import com.upyun.UpYunUtils;
import io.swagger.models.auth.In;
import lombok.Data;
import okhttp3.OkHttpClient;
import okhttp3.Response;
import okhttp3.ResponseBody;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;
import org.springframework.web.multipart.MultipartFile;

import java.io.BufferedOutputStream;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.*;
import java.util.logging.Level;
import java.util.logging.Logger;

/**
 * @author zhz
 * @date 2021/6/15 12:42
 * 备注：又拍云工具类整合，如需添加功能，可查看：https://github.com/upyun/java-sdk
 */
@Component
public class UploadToYun {

    @Value("${UPYun.bucketName}")
    private String bucketName;
    @Value("${UPYun.userName}")
    private String userName;
    @Value("${UPYun.password}")
    private String password;
    @Value("${UPYun.documentName}")
    private String documentName;
    @Value("${path.download}")
    private String filePath;

    private RestManager manager=null;

    public String getFilePath() {
        return filePath;
    }

    private void newManager(RestManager manager){
        if (manager == null)
            synchronized (this) {
                if (manager == null) {
                    this.manager = new NewManager(bucketName, userName, password).getManager();
                }
            }
    }
    private Boolean isFileExists(String filePath) throws IOException, UpException {
        newManager(manager);
        Response response = manager.getFileInfo(filePath);
        return response.isSuccessful();
    }
    /**
     * 上传文件，路径自动生成：年_月+UUID+文件名
     * @param file 文件
     * @return 成功返回true，失败抛出异常，原位置已存在文件返回false
     * @throws Exception
     */
    public String saveFile(MultipartFile file) throws Exception {
        String calendar = Calendar.getInstance().get(Calendar.YEAR)+"_"+(Calendar.getInstance().get(Calendar.MONTH)+1);
        //地址 = 年_月+UUID+文件名
        String filePath = calendar+"/"+UUID.randomUUID() + file.getOriginalFilename();
        return saveFile(file,filePath);
    }

    /**
     * 上传文件，路径可自定义，但必须在/reward文件下，文件可能重命名（会返回异常）
     * 可用于将文件暂存与temp下
     * @param file 上传的文件
     * @param filePath 文件路径，默认会在路径前加上"/reward/"(documentName)
     * @return 成功返回true，失败抛出异常，原位置已存在文件false
     * @throws Exception
     */
    public String saveFile(MultipartFile file,String filePath) throws Exception {
        newManager(manager);
        manager.setApiDomain(RestManager.ED_AUTO);//选择最优的接入点
        filePath = documentName+filePath;
        if(isFileExists(filePath)){
            return null;
        }
        Map<String, String> params = new HashMap<>();
        params.put("Date", UpYunUtils.getGMTDate());
        params.put("Content-Length", String.valueOf(file.getSize()));
        boolean isUpdate = manager.writeFile(filePath, file.getBytes(), params).isSuccessful();
        if (!isUpdate) {
            System.out.println("{文件服务}文件上传失败又拍云异常");
            System.out.println(manager.writeFile(filePath, file.getBytes(), params).toString());
            throw new UpException("文件过大，文件上传失败");
        }
        return filePath;
    }
    /*
     * 从本地路径获取文件，用于辅助实现文件下载功能
     * 目前初步思路是返回一个byte数组，但可能有问题，以后实际用了再慢慢改
     * 参考资料地址：
     * 1、https://blog.csdn.net/user2025/article/details/107300831
     * 2、https://www.cnblogs.com/kzyuan/p/12493993.html
     *
     * filePath : String  文件在本地的存储路径
     * */
    public ResponseBody downloadFile(String filePath) throws IOException, UpException {
        newManager(manager);
//        System.out.println(filePath);
        String fname = filePath.split("cn/",2)[1];
        manager.setApiDomain(RestManager.ED_AUTO);//选择最优的接入点
        Response response = manager.readFile(fname);
        if(response.isSuccessful()){
            return response.body();
        }
        throw new UpException("文件不存在，下载失败");
    }
    /**
     * 根据byte数组，生成文件
     */
    public void getFile(byte[] bfile,String fileName) {
        fileName = filePath+fileName;
        BufferedOutputStream bos = null;
        FileOutputStream fos = null;
        File file = null;
        try {
//            File dir = new File(filePath);
//            if(!dir.exists()&&dir.isDirectory()){//判断文件目录是否存在
//                dir.mkdirs();
//            }
            file = new File(fileName);
            fos = new FileOutputStream(file);
            bos = new BufferedOutputStream(fos);
            bos.write(bfile);
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            if (bos != null) {
                try {
                    bos.close();
                } catch (IOException e1) {
                    e1.printStackTrace();
                }
            }
            if (fos != null) {
                try {
                    fos.close();
                } catch (IOException e1) {
                    e1.printStackTrace();
                }
            }
        }
    }

    static class NewManager{
        private static RestManager manager;
        NewManager(String bucketName,String userName,String password){
            this.manager=new RestManager(bucketName,userName,password);
        }
        public RestManager getManager() {
            return manager;
        }
    }
}